package main

import (
	"context"
	"github.com/golang/protobuf/proto"
	"google.golang.org/grpc/reflection/grpc_reflection_v1alpha"
	"google.golang.org/protobuf/types/descriptorpb"
	"log"

	"google.golang.org/grpc"
)

func main() {
	// Set up a connection to the server.
	conn, err := grpc.Dial("localhost:50051", grpc.WithInsecure())
	if err != nil {
		log.Fatalf("did not connect: %v", err)
	}
	defer conn.Close()

	c := grpc_reflection_v1alpha.NewServerReflectionClient(conn)
	client, err := c.ServerReflectionInfo(context.Background())
	if err != nil {
		log.Fatalf("ServerReflectionInfo err:%v", err)
		return
	}

	// 1. 获取Service List
	req := grpc_reflection_v1alpha.ServerReflectionRequest{
		MessageRequest: &grpc_reflection_v1alpha.ServerReflectionRequest_ListServices{},
	}
	client.Send(&req)
	r, err := client.Recv()
	if err != nil {
		log.Fatalf("recv: %v", err)
		return
	}
	log.Printf("ServiceList:%v", r.GetListServicesResponse().String())

	// 2.
	req = grpc_reflection_v1alpha.ServerReflectionRequest{
		MessageRequest: &grpc_reflection_v1alpha.ServerReflectionRequest_FileContainingSymbol{
			FileContainingSymbol: "Greeter",
		},
	}
	client.Send(&req)
	r, err = client.Recv()
	if err != nil {
		log.Fatalf("recv: %v", err)
		return
	}

	fd := new(descriptorpb.FileDescriptorProto)
	if err := proto.Unmarshal(r.GetFileDescriptorResponse().GetFileDescriptorProto()[0], fd); err != nil {
		log.Fatalf("unmarshal file descriptor : %v", err)
		return
	}
	log.Printf("FileDescriptor:%v", fd.String())

}
